package com.bw.publish.utils

import android.content.Context
import com.alibaba.sdk.android.oss.ClientConfiguration
import com.alibaba.sdk.android.oss.ClientException
import com.alibaba.sdk.android.oss.OSSClient
import com.alibaba.sdk.android.oss.ServiceException
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask
import com.alibaba.sdk.android.oss.model.PutObjectRequest
import com.alibaba.sdk.android.oss.model.PutObjectResult
import com.bw.lib_common.BaseApp


object OSSUtils {
    // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
    var endpoint: String = "oss-cn-beijing.aliyuncs.com"

    // 从STS服务获取的临时访问密钥（AccessKey ID和AccessKey Secret）。
    var accessKeyId: String = "LTAI5tGY3rxNPnxiGqvqCrmm"
    var accessKeySecret: String = "peAexjUQVs7AHPyAILW8MBQ8JkCa8S"

    // 从STS服务获取的安全令牌（SecurityToken）。
//    var securityToken: String = "yourSecurityToken"


    var ossClient: OSSClient

    val bucket: String = "zg-5-demo"

    init {
        ossClient = getOSS(BaseApp.getContext())
    }

    fun getOSS(context: Context): OSSClient {
        val configuration = ClientConfiguration()
        // 设置最大并发数，默认值5。
        configuration.setMaxConcurrentRequest(3);
        // 设置Socket层传输数据的超时时间，默认值60s。
        configuration.setSocketTimeout(50000);
        // 设置建立连接的超时时间，默认值60s。
        configuration.setConnectionTimeout(50000);
        // 设置日志文件大小，默认值5 MB。
        configuration.setMaxLogSize(3 * 1024 * 1024);
        // 请求失败后最大的重试次数，默认值2。
        configuration.setMaxErrorRetry(3);

        var oSSPlainTextAKSKCredentialProvider: OSSPlainTextAKSKCredentialProvider =
            OSSPlainTextAKSKCredentialProvider(accessKeyId, accessKeySecret)

        // 创建OSSClient实例。
        var oss: OSSClient =
            OSSClient(context, endpoint, oSSPlainTextAKSKCredentialProvider, configuration)

        return oss
    }

    fun upLoadObject(name: String, path: String, callBack: CallBack) {
        val put = PutObjectRequest(bucket, name, path)

        val task: OSSAsyncTask<*> = ossClient.asyncPutObject(
            put,
            object : OSSCompletedCallback<PutObjectRequest?, PutObjectResult> {
                override fun onSuccess(request: PutObjectRequest?, result: PutObjectResult) {
                    callBack.onSuccess(true)
                }

                override fun onFailure(
                    request: PutObjectRequest?,
                    clientExcepion: ClientException,
                    serviceException: ServiceException
                ) {
                    // 异常处理。
                    callBack.onFailed(RuntimeException(clientExcepion.message + serviceException.message))
                }
            })
    }


}